package com.roast.services.my;

import com.roast.domain.Event;
import com.roast.util.QueryObject;
import com.roast.util.QueryBeanFactory;

public class CreateIMPL extends GeneralSO implements Create {

    private Event event;
    private QueryObject queryObject;

    @Override
    public int create(Event event) {
        return new CreateIMPL().generalExecution(event);
    }

    @Override
    protected int executeSO(Object obj) {
        if (!setEvent(obj)) {
            return 10501;
        }
        if (!setQuery("readEventMasterStar")) {
            return 10502;
        }
        if (checkEventMasterAndStar()) {
            return 10503;
        }
        if (!saveEvent()) {
            return 10504;
        }
        return 10500;
    }

    private boolean setEvent(Object obj) {
        try {
            this.event = (Event) obj;
            return true;
        } catch (ClassCastException ex) {
            return false;
        }
    }

    private boolean setQuery(String beanID) {
        queryObject = QueryBeanFactory.getBean(beanID);
        if (queryObject == null) {
            return false;
        }

        if (queryObject.addParametar("masterid", event.getMaster().getUserID())) {
            return queryObject.addParametar("starid", event.getStar().getUserID());
        }
        return false;
    }

    private boolean checkEventMasterAndStar() {
        try {
            dbbr.readOneByParametar(queryObject);
        } catch (NullPointerException ex) {
            System.out.println("[GetPublicEvents:checkEventMasterAndStar:[" + ex + "]]");
            return false;
        }
        return queryObject.getSignal() == 10030;
    }

    private boolean saveEvent() {
        return dbbr.save(event);
    }

    @Override
    protected boolean executeState(int signal) {
        switch (signal) {
            case 10500:
                showOperationState(signal, "create: You have successfully create event.");
                return true;
            case 10501:
                showOperationState(signal, "create:ERROR: Class cast exception.");
                return false;
            case 12002:
                showOperationState(signal, "create:ERROR: Fail to set query readEventMasterStar.");
                return false;
            case 10503:
                showOperationState(signal, "create:ERROR: Event with that master and star already exist.");
                return false;
            case 10504:
                showOperationState(signal, "create:ERROR: You fail to create event.");
                return false;
        }
        return false;
    }
}
